package com.cloud.media.api.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.cloud.media.api.service.MediaStorageService;
import com.cloud.media.common.consts.MediaConsts;
import com.cloud.media.interfaces.FeignClientSystem;

@Service
public class MediaStorageServiceImpl implements MediaStorageService {
	private static final Logger logger = LoggerFactory.getLogger(MediaStorageServiceImpl.class);
	@Autowired
	private FeignClientSystem feignClientSystem;

	@Override
	public void upload(MultipartFile file, String path) {
		String mediaRootPath = feignClientSystem.getMediaRootPath(MediaConsts.DEFAULT_MEDIA_ROOT_PATH_CONFIG,
				MediaConsts.DEFAULT_MEIDA_ROOT);
		File f = new File(mediaRootPath + path);
		if (logger.isDebugEnabled()) {
			logger.debug("上传文件{}{}", mediaRootPath, path);
		}
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), f);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public InputStream download(String path) {
		String mediaRootPath = feignClientSystem.getMediaRootPath(MediaConsts.DEFAULT_MEDIA_ROOT_PATH_CONFIG,
				MediaConsts.DEFAULT_MEIDA_ROOT);
		File f = new File(mediaRootPath + path);
		try {
			return FileUtils.openInputStream(f);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	public void delete(String path) {
		String mediaRootPath = feignClientSystem.getMediaRootPath(MediaConsts.DEFAULT_MEDIA_ROOT_PATH_CONFIG,
				MediaConsts.DEFAULT_MEIDA_ROOT);
		File f = new File(mediaRootPath + path);
		FileUtils.deleteQuietly(f);
	}

}
